import javax.swing.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2025-08-24
 * Time: 19:43
 */
//模拟实现阻塞队列
class MyQueue{
    private String[] queue=null;
    private int size=0;
    private int max_size=0;
    private int head=0;
    private int last=0;

    public MyQueue(){
        queue=new String[50];
        max_size=50;
    }
    public MyQueue(int n){
        queue=new String[n];
        max_size=n;
    }
    public String put(String str){
        try{
            if(isFull()){
                synchronized (this){
                    this.wait();
                }
            }
            synchronized(this){
                queue[last]=str;
                size++;last++;
                if(last==max_size){
                    last=0;
                }
                this.notify();
                return str;
            }
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
        return str;
    }
    public String take(){
        try{
            if(isEmpty()){
                synchronized(this){
                    this.wait();
                }
            }
            synchronized (this){
                int x=head;
                size--;head++;
                if (head==max_size){
                    head=0;
                }
                this.notify();
                return queue[x];
            }
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
        return null;
    }
    private boolean isFull(){
        return size==max_size;
    }
    private boolean isEmpty(){
        return size==0;
    }

}
public class Test {
    public static void main(String[] args) {
        MyQueue queue=new MyQueue(10);
        //t1模拟生产者
        Thread t1=new Thread() {
            @Override
            public void run() {
                try {
                    for (int i = 1; i <= 100; i++) {
                        sleep(300);
                        System.out.println("生产" + queue.put("产品" + i));
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        //t2模拟消费者
        Thread t2=new Thread() {
            @Override
            public void run() {
                try {
                    for (int i = 1; i <= 100; i++) {
                        sleep(1000);
                        System.out.println("购买产品" + queue.take());
                    }
                    ;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };
        t1.start();
        t2.start();
    }

}
